package com.consumer.listener;

import com.rabbitmq.client.Channel;
import com.rb.config.DeadQueueConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.io.IOException;

/**
 * @program: SpringBootDemos
 * @description: 接收mq消息
 * @author: Kangsen
 * @create: 2021-08-24 11:03
 **/
@Component
@Slf4j
public class ReceiveListener {

    //监听业务A
    @RabbitListener(queues = DeadQueueConfig.QUEUE_BUSINESS_A)
    public void receiveBusinessA(Message message, Channel channel) throws IOException {
        String msg = new String(message.getBody());
        log.info("收到业务消息A：{}", msg);
        boolean ack = true;
        Exception exception = null;
        try {
            if (msg.contains("deadLetter")){
                throw new RuntimeException("dead letter exception");
            }
        } catch (Exception e){
            ack = false;
            exception = e;
        }
        if (!ack){
            log.error("消息消费发生异常，error msg:{}", exception.getMessage(), exception);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        } else {
            log.info("接受消息");
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

    //监听业务B
    @RabbitListener(queues = DeadQueueConfig.QUEUE_BUSINESS_B)
    public void receiveBusinessB(Message message, Channel channel) throws IOException {
        System.out.println("收到业务消息B：" + new String(message.getBody()));
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    //监听死信队列
    @RabbitListener(queues = DeadQueueConfig.QUEUE_DEAD)
    public void receiveDeadA(Message message, Channel channel) throws IOException {
        System.out.println("收到死信消息A：" + new String(message.getBody()));
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
